 package cn.watson.asynchronous;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.common.message.MessageExt;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @Description: 消费者
 * @Author: Zhangrui
 * @Version: 1.0
 * @Date:  2022/7/25 20:48
 */
public class Consumer {


    public static void main(String[] args) throws Exception {
        // 1.创建消费者对象，指定消费者组名
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("Producer_asyn_group");
        // 2.链接MQ 设置NameServer的地址
        consumer.setNamesrvAddr("127.0.0.1:9876");
        // 3.消费者订阅主题，表示要消费那个消费者的消息。可以是* 表示所有
        consumer.subscribe("hello_topic2", "hello_tags2");
        // 4.注册监听器
        consumer.registerMessageListener((List<MessageExt> msgs, ConsumeConcurrentlyContext context) -> {
            for (MessageExt msg : msgs) {
                String result = new String(msg.getBody(), StandardCharsets.UTF_8);
                System.out.println(result);
            }
            // 标记该消息已经被成功消费
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        });
        // 5.启动消费者
        consumer.start();
        System.out.println("Consumer Started.%n");
    }

}





















